package cn.christ.com.mobilesafe.view.activity_appmanager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.text.format.Formatter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import cn.christ.com.mobilesafe.R;
import cn.christ.com.mobilesafe.common.BaseActivity;
import cn.christ.com.mobilesafe.common.Global;
import cn.christ.com.mobilesafe.engine.AppProvider;
import cn.christ.com.mobilesafe.modle.AppInfo;
import cn.christ.com.mobilesafe.view.widgets.DesProgressView;

/**
 * Created by Administrator on 2018/7/24.
 */

public class AppManagerActivity extends BaseActivity {
    @BindView(R.id.dpv_rom)
    DesProgressView dpvRom;
    @BindView(R.id.dpv_sd)
    DesProgressView dpvSd;
    @BindView(R.id.lv_app_manager)
    ListView lvAppManager;
    @BindView(R.id.ll_loading)
    LinearLayout llLoading;
    @BindView(R.id.tv_app_head_ref)
    TextView tvAppHead;


    private List<AppInfo> appInfos;
    private List<AppInfo> sysInfos = new ArrayList<AppInfo>();
    private List<AppInfo> userInfos = new ArrayList<AppInfo>();
    private AppInfo mAppInfo;
    private UnInstallReceiver mUnInstallReceiver;
    private AppManagerAdapter mAppManagerAdapter;

    @Override
    public int getLayoutRes() {
        return R.layout.activity_app_manager;
    }

    @Override
    public void initListener() {
// 初始化事件
        lvAppManager.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            private PopupWindow mPopupWindow;

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // // 1 第一种方案
                // if(position==userInfos.size()){
                // return;
                // }
                // 获取用户集合的AppInfo
                if (position < userInfos.size()) {
                    mAppInfo = userInfos.get(position);
                } else {
                    mAppInfo = sysInfos.get(position - userInfos.size() - 1);
                }

                // 1 构建PopupWindow
                View contentView = View.inflate(getApplicationContext(), R.layout.view_app_popup, null);
                if (mPopupWindow == null) {
                    mPopupWindow = new PopupWindow(contentView, 800, view.getHeight(), true);
                }
                mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffffffff")));// #ffffffff--->int
                mPopupWindow.setOutsideTouchable(true);
                // 2 显示PopupWindow
                mPopupWindow.showAsDropDown(view, 65, -view.getHeight());
                // 3 细节处理
                // 卸载
                contentView.findViewById(R.id.tv_uninstall).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        /*
                         * <intent-filter> <action
						 * android:name="android.intent.action.VIEW" /> <action
						 * android:name="android.intent.action.DELETE" />
						 * <category
						 * android:name="android.intent.category.DEFAULT" />
						 * <data android:scheme="package" /> </intent-filter>
						 */
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.DELETE");
                        intent.addCategory("android.intent.category.DEFAULT");
                        intent.setData(Uri.parse("package:" + mAppInfo.packageName));
                        startActivity(intent);
                        // 隐藏对话框
                        mPopupWindow.dismiss();
                    }
                });

                // 打开应用
                contentView.findViewById(R.id.tv_open).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // try {
                        // PackageManager pm = getPackageManager();
                        // // 通过包名获取Intent
                        // Intent intent =
                        // pm.getLaunchIntentForPackage(mAppInfo.packageName);
                        // startActivity(intent);
                        // } catch (Exception e) {
                        // Toast.makeText(getApplicationContext(),
                        // "您的应用太NB的，我无卸载您", 0).show();
                        // }
                        PackageManager pm = getPackageManager();
                        // 通过包名获取Intent
                        Intent intent = pm.getLaunchIntentForPackage(mAppInfo.packageName);
                        if (intent != null) {
                            startActivity(intent);
                        } else {
                            Global.showToast("您的应用太NB的，我无卸载您");
                        }
                        // 隐藏对话框
                        mPopupWindow.dismiss();
                    }
                });

                // 分享：
                contentView.findViewById(R.id.tv_share).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // 隐藏对话框
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.SENDTO");// 发送信息的动作
                        intent.addCategory("android.intent.category.DEFAULT");// 附加信息
                        intent.putExtra("sms_body", "分享广州christ安全卫士");
                        intent.setData(Uri.parse("sms:10086"));// 具体的数据，发送给10086
                        startActivity(intent);
                        mPopupWindow.dismiss();
                    }
                });
                // 详细信息
                contentView.findViewById(R.id.tv_info).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // 隐藏对话框
                        Intent intent = new Intent();
                        intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                        intent.addCategory("android.intent.category.DEFAULT");
                        intent.setData(Uri.parse("package:" + mAppInfo.packageName));
                        startActivity(intent);
                        mPopupWindow.dismiss();
                    }
                });

            }
        });
    }

    @Override
    public void initData() {
        initHeadData();// 初始化头部数据
        // 加载软件的数据
        tvAppHead.setVisibility(View.GONE);
        new Thread(new Runnable() {

            @Override
            public void run() {
                // 加载数据

                appInfos = AppProvider.getAppInfos(getApplicationContext());
                // 区分系统和用户的集合
                for (AppInfo appInfo : appInfos) {
                    if (appInfo.isSystem) {
                        sysInfos.add(appInfo);
                    } else {
                        userInfos.add(appInfo);
                    }
                }
                // 加载完数据之后，更新UI
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        mAppManagerAdapter = new AppManagerAdapter();
                        lvAppManager.setAdapter(mAppManagerAdapter);
                        llLoading.setVisibility(View.GONE);
                        tvAppHead.setText("用户程序：(" + userInfos.size() + ")个");
                        tvAppHead.setVisibility(View.VISIBLE);
                    }
                });
            }
        }).start();

        // 注册卸载广播
        mUnInstallReceiver = new UnInstallReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter.addDataScheme("package");
        registerReceiver(mUnInstallReceiver, filter);
    }

    private void initHeadData() {
        // 初始化内部存储卡的数据
        initRomData();
        // 初始化外部存储卡的数据
        initSDData();
    }

    private void initRomData() {
        File dataDirectory = Environment.getDataDirectory();
        long dataTotalSpace = dataDirectory.getTotalSpace();// 1M=1024kb=1024*1024Bytes
        // String formatFileSize =
        // Formatter.formatFileSize(getApplicationContext(), dataTotalSpace);
        long dataUsableSpace = dataDirectory.getUsableSpace();
        long dataUsedSpace = dataTotalSpace - dataUsableSpace;
        dpvRom.setLeftType(Formatter.formatFileSize(getApplicationContext(), dataUsedSpace));
        dpvRom.setRightType(Formatter.formatFileSize(getApplicationContext(), dataTotalSpace));
        dpvRom.setProgress((int) (dataUsedSpace * 100 / dataTotalSpace));// 小数0.59*100
    }

    private void initSDData() {
        if (Environment.getExternalStorageDirectory().equals(Environment.MEDIA_MOUNTED)) {
            File externalStorageDirectory = Environment.getExternalStorageDirectory();
            long sdTotalSpace = externalStorageDirectory.getTotalSpace();
            long sdUsableSpace = externalStorageDirectory.getUsableSpace();
            long sdUsedSpace = sdTotalSpace - sdUsableSpace;
            dpvSd.setLeftType(Formatter.formatFileSize(getApplicationContext(), sdUsedSpace));
            dpvSd.setRightType(Formatter.formatFileSize(getApplicationContext(), sdTotalSpace));
            dpvSd.setProgress((int) (sdUsedSpace * 100 / sdTotalSpace));
        }else {
            dpvSd.setLeftType("0 GB");
            dpvSd.setRightType("0 GB");
            dpvSd.setProgress(0);
        }

    }


    class AppManagerAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return userInfos.size() + sysInfos.size() + 1;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (position == userInfos.size()) {
                TextView tv = (TextView) View.inflate(getApplicationContext(), R.layout.tv_app_head, null);
                tv.setTextColor(Color.BLACK);
                tv.setText("系统程序：(" + sysInfos.size() + ")个");
                return tv;
            }
            ViewHolder holder;
            if (convertView == null || convertView instanceof TextView) {// TextView
                holder = new ViewHolder();
                convertView = View.inflate(getApplicationContext(), R.layout.view_lv_app_item, null);
                holder.ivAppIcon = (ImageView) convertView.findViewById(R.id.iv_app_icon);
                holder.tvAppName = (TextView) convertView.findViewById(R.id.tv_app_name);
                holder.tvAppInstall = (TextView) convertView.findViewById(R.id.tv_app_install);
                holder.tvAppSize = (TextView) convertView.findViewById(R.id.tv_app_size);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            // 1 通过position获取软件的数据
            AppInfo appInfo = null;
            if (position < userInfos.size()) {
                appInfo = userInfos.get(position);
            } else {
                appInfo = sysInfos.get(position - userInfos.size() - 1);
            }
            // 2 设置数据
            holder.tvAppName.setText(appInfo.name);
            holder.ivAppIcon.setImageDrawable(appInfo.icon);
            holder.tvAppSize.setText(Formatter.formatFileSize(getApplicationContext(), appInfo.apkSize));
            holder.tvAppInstall.setText(appInfo.isInstallSD ? "SD卡" : "手机内存");
            return convertView;
        }

        @Override
        public boolean isEnabled(int position) {
            return position == userInfos.size() ? false : true;
        }
    }

    class ViewHolder {
        public ImageView ivAppIcon;
        public TextView tvAppName;
        public TextView tvAppInstall;
        public TextView tvAppSize;
    }

    // 卸载广播
    class UnInstallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 1 获取卸载的包名
            String data = intent.getDataString();
            String packageName = data.replace("package:", "");
            // 2 从集合删除该包名的实体bean
            // for (AppInfo info : appInfos) {
            // if(info.packageName.equals(packageName)){
            // appInfos.remove(info);
            // }
            // }
            Iterator<AppInfo> iterator = userInfos.iterator();
            while (iterator.hasNext()) {
                AppInfo info = iterator.next();
                if (info.packageName.equals(packageName)) {
                    iterator.remove();
                    break;
                }
            }
            // 3 更新UI
            if (mAppManagerAdapter != null) {
                mAppManagerAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUnInstallReceiver != null) {
            unregisterReceiver(mUnInstallReceiver);
        }
    }

    @Override
    public void initPresenter() {

    }

}
